﻿namespace Baula.TextGen.ActiveTemplating
{
    public class Engine
    {
        private readonly TemplateToVBConverter _converter;
        private readonly IExecutor _executor;
        private readonly IDefaultContextMapping _defaultContextMapping;

        public Engine(TemplateToVBConverter converter, IExecutor executor, IDefaultContextMapping defaultContextMapping)
        {
            _converter = converter;
            _executor = executor;
            _defaultContextMapping = defaultContextMapping;

            Setup();
        }

        public Engine(IContext context)
            : this(new TemplateToVBConverter(), new Executor(context), new DefaultContextMapping())
        { }

        private void Setup()
        {
            foreach (var wellKnownPlaceholder in _defaultContextMapping.WellKnownPlaceholders)
            {
                var code = _defaultContextMapping.GetCodeForWellKnownPlaceholder(wellKnownPlaceholder);
                _converter.AddWellknownExpression(wellKnownPlaceholder, code);
            }
        }

        public string Process(string templateText)
        {
            var code = _converter.Convert(templateText);
            _executor.Execute(code);
            return _executor.Output;
        }
    }
}
